<script setup lang="ts">
import { getMessageList, getSession, readMessage } from '@/api/message';
import { Message, MessageList, Session } from '@/api/message/type';
import Header from './components/Header.vue';
import Bottom from './components/Bottom.vue';
import { useUserStore } from '@/store/user';
import { onMounted, ref, nextTick, onUnmounted } from 'vue';
import { useRoute } from 'vue-router';
import { showNotify } from 'vant';

const messageList = ref({} as MessageList);
const userId = ref('');
const session = ref({} as Session);
const chatContent = ref<HTMLDivElement>();
let eventSource: EventSource | null = null;
const loading = ref(true);

onMounted(() => {
    const userStore = useUserStore();
    userId.value = userStore.getId;
    session.value.senderId = userId.value;
    
    const route = useRoute();
    session.value.receiverId = route.query.receiverId as string;
    session.value.id = route.query.sessionId as string;
    
    if (session.value.id === undefined) {
        initSession();
    } else {
        refresh();
        setupMessageStream();
    }
})

onUnmounted(() => {
    // 在组件卸载时关闭事件流
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
})

const initSession = async () => {
    try {
        const res = await getSession(session.value);
        session.value = res.data as Session;
        refresh();
        setupMessageStream();
    } catch (error) {
        console.error('初始化会话失败:', error);
        showNotify({
            type: 'danger',
            message: '初始化会话失败',
            position: 'top'
        });
    }
}

const refresh = async () => {
    if (session.value.id === undefined) return;
    
    try {
        loading.value = true;
        const res = await getMessageList(session.value.id);
        const {receiver, sender, list} = res.data as MessageList;
        
        if (userId.value === sender.id) {
            messageList.value.sender = sender;
            messageList.value.receiver = receiver;
        } else {
            messageList.value.sender = receiver;
            messageList.value.receiver = sender;
        }
        
        messageList.value.list = list || [];
        
        // 标记消息为已读
        await readMessage(session.value.id, session.value.senderId);
        
        // 滚动到底部
        scrollToBottom();
    } catch (error) {
        console.error('获取消息列表失败:', error);
    } finally {
        loading.value = false;
    }
}

function setupMessageStream() {
    // 关闭之前的连接（如果存在）
    if (eventSource) {
        eventSource.close();
    }
    
    // 创建新的 EventSource 连接
    eventSource = new EventSource(`/api/chat/stream?sessionId=${session.value.id}`);
    
    // 监听聊天消息
    eventSource.addEventListener('message', (event) => {
        try {
            const message = JSON.parse(event.data) as Message;
            if (!messageList.value.list) {
                messageList.value.list = [];
            }
            
            messageList.value.list.push(message);
            readMessage(session.value.id, session.value.senderId);
            scrollToBottom();
            
            // 显示消息通知
            showNotification('消息', '你收到来自好友的一条消息！');
        } catch (error) {
            console.error('解析消息失败:', error);
        }
    });
    
    // 错误处理
    eventSource.onerror = () => {
        if (eventSource) {
            eventSource.close();
            setTimeout(() => setupMessageStream(), 5000); // 5秒后尝试重连
        }
    };
}

// 使用Web Notifications API
function showNotification(title: string, body: string) {
    // 检查通知权限
    if (!('Notification' in window)) {
        console.log('This browser does not support notifications');
        return;
    }
    
    if (Notification.permission === 'granted') {
        new Notification(title, { body });
    } else if (Notification.permission !== 'denied') {
        // 请求通知权限
        Notification.requestPermission().then(permission => {
            if (permission === 'granted') {
                new Notification(title, { body });
            }
        });
    }
}

const scrollToBottom = () => {
    nextTick(() => {
        if (chatContent.value) {
            chatContent.value.scrollTop = chatContent.value.scrollHeight;
        }
    });
}

// 格式化时间 - 修改为支持简单时间格式
const formatTime = (time: string) => {
    if (!time) return '';
    
    // 检查是否是简单时间格式 (HH:MM:SS)
    if (/^\d{2}:\d{2}:\d{2}$/.test(time)) {
        return time.substring(0, 5); // 只显示小时和分钟
    }
    
    // 如果是完整日期时间格式，使用原来的解析方式
    try {
        const date = new Date(time);
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } catch (error) {
        console.error('时间格式解析错误:', error);
        return time; // 返回原始时间字符串
    }
}

// 判断是否需要显示日期分隔 - 修改为支持简单时间格式
const shouldShowDateDivider = (current: Message, previous: Message | undefined, index: number) => {
    if (!previous || index === 0) return true;
    
    // 如果是简单时间格式，无法判断日期变更，默认不显示分隔线
    if (/^\d{2}:\d{2}:\d{2}$/.test(current.sendTime)) {
        return false;
    }
    
    try {
        const currentDate = new Date(current.sendTime).toDateString();
        const previousDate = new Date(previous.sendTime).toDateString();
        return currentDate !== previousDate;
    } catch (error) {
        console.error('日期比较错误:', error);
        return false;
    }
}

// 格式化日期显示 - 修改为支持简单时间格式
const formatDate = (time: string) => {
    if (!time) return '';
    
    // 如果是简单时间格式，返回今天
    if (/^\d{2}:\d{2}:\d{2}$/.test(time)) {
        return '今天';
    }
    
    try {
        const date = new Date(time);
        return date.toLocaleDateString('zh-CN', { 
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            weekday: 'long'
        });
    } catch (error) {
        console.error('日期格式化错误:', error);
        return '未知日期';
    }
}
</script>

<template>
    <div class="chat-container">
        <!-- 聊天头部 -->
        <Header class="chat-header" />
        
        <!-- 聊天内容区域 -->
        <div class="chat-content-wrapper">
            <!-- 加载状态 -->
            <div v-if="loading" class="chat-loading">
                <van-loading type="spinner" vertical>加载聊天记录中...</van-loading>
            </div>
            
            <!-- 聊天消息 -->
            <div v-else ref="chatContent" class="chat-messages">
                <div v-if="messageList.list && messageList.list.length === 0" class="empty-chat">
                    <van-empty description="暂无聊天记录">
                        <template #default>
                            <p class="start-chat-tip">发送消息开始聊天吧</p>
                        </template>
                    </van-empty>
                </div>
                
                <template v-else>
                    <!-- 消息列表 -->
                    <div 
                        v-for="(message, index) in messageList.list" 
                        :key="index"
                        class="message-container"
                    >
                        <!-- 日期分隔线 -->
                        <div 
                            v-if="shouldShowDateDivider(message, messageList.list[index-1], index)"
                            class="date-divider"
                        >
                            <span>{{ formatDate(message.sendTime) }}</span>
                        </div>
                        
                        <!-- 接收的消息 -->
                        <div 
                            v-if="userId !== message.senderId"
                            class="message received"
                        >
                            <div class="avatar-container">
                                <van-image 
                                    :src="messageList.receiver.avatar" 
                                    round 
                                    width="40" 
                                    height="40"
                                    fit="cover"
                                />
                            </div>
                            <div class="message-content">
                                <div class="message-sender">
                                    {{ messageList.receiver.nickname }}
                                </div>
                                <div class="message-bubble">
                                    {{ message.content }}
                                </div>
                                <div class="message-time">
                                    {{ formatTime(message.sendTime) }}
                                </div>
                            </div>
                        </div>
                        
                        <!-- 发送的消息 -->
                        <div 
                            v-else
                            class="message sent"
                        >
                            <div class="message-content">
                                <div class="message-bubble">
                                    {{ message.content }}
                                </div>
                                <div class="message-time">
                                    {{ formatTime(message.sendTime) }}
                                </div>
                            </div>
                            <div class="avatar-container">
                                <van-image 
                                    :src="messageList.sender.avatar" 
                                    round 
                                    width="40" 
                                    height="40"
                                    fit="cover"
                                />
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
        
        <!-- 输入框区域 -->
        <div class="chat-input">
            <Bottom 
                v-model:session="session" 
                v-model:user-id="userId"
                @send="refresh"
            />
        </div>
    </div>
</template>

<style lang="scss" scoped>
.chat-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 108px);
    background-color: #f7f8fa;
    
    .chat-header {
        flex-shrink: 0;
        background-color: white;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }
    
    .chat-content-wrapper {
        flex: 1;
        overflow-y: auto;
        padding: 16px;
        
        .chat-loading,
        .empty-chat {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            
            .start-chat-tip {
                margin-top: 16px;
                font-size: 14px;
                color: #969799;
            }
        }
        
        .chat-messages {
            display: flex;
            flex-direction: column;
            max-width: 800px;
            margin: 0 auto;
            padding-bottom: 16px;
            
            .date-divider {
                display: flex;
                justify-content: center;
                margin: 16px 0;
                
                span {
                    background-color: rgba(0, 0, 0, 0.05);
                    padding: 4px 12px;
                    border-radius: 16px;
                    font-size: 12px;
                    color: #909399;
                }
            }
            
            .message-container {
                margin-bottom: 16px;
            }
            
            .message {
                display: flex;
                margin-bottom: 8px;
                
                &.received {
                    align-items: flex-start;
                    
                    .avatar-container {
                        margin-right: 12px;
                    }
                    
                    .message-bubble {
                        background-color: white;
                        border-radius: 0 12px 12px 12px;
                    }
                }
                
                &.sent {
                    align-items: flex-start;
                    justify-content: flex-end;
                    
                    .avatar-container {
                        margin-left: 12px;
                    }
                    
                    .message-content {
                        align-items: flex-end;
                        
                        .message-sender {
                            text-align: right;
                        }
                        
                        .message-bubble {
                            background-color: #007fff;
                            color: white;
                            border-radius: 12px 0 12px 12px;
                        }
                        
                        .message-time {
                            text-align: right;
                        }
                    }
                }
                
                .avatar-container {
                    flex-shrink: 0;
                }
                
                .message-content {
                    display: flex;
                    flex-direction: column;
                    max-width: 70%;
                    
                    .message-sender {
                        font-size: 12px;
                        color: #909399;
                        margin-bottom: 4px;
                    }
                    
                    .message-bubble {
                        padding: 12px 16px;
                        font-size: 15px;
                        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
                        word-break: break-word;
                    }
                    
                    .message-time {
                        margin-top: 4px;
                        font-size: 12px;
                        color: #909399;
                    }
                }
            }
        }
    }
    
    .chat-input {
        flex-shrink: 0;
        background-color: white;
        border-top: 1px solid #f2f3f5;
    }
}
</style>